<?php 
    namespace Mark\Repository;
    
    class MarkVideoRepository extends AbstractRepository {
        protected  $entity="Mark\\Entity\\MarkVideo";
        
    
        
        
        public function listByVideo($idVideo, $maxResult=null){
            $dql = "SELECT c FROM $this->entity c JOIN c.video v WHERE v.id = ?1";
            $query = $this->getEntityManager()->createQuery($dql)
                ->setParameter(1, $idVideo);
            if($maxResult!=null && $maxResult>0) $query->setMaxResults($maxResult);
            return $query->getResult();
        }

        public function listByVideo2($idVideo, $maxId=null, $limit=null){
        	$dql = "SELECT c FROM $this->entity c WHERE IDENTITY(c.video) = ?1";
        	if($maxId!=null && $maxId>0) $dql.=" AND c.id < ?2";
        	$dql .= " ORDER BY c.id desc";
        	$query = $this->getEntityManager()->createQuery($dql)
        	->setParameter(1, $idVideo);
        	if($maxId!=null && $maxId>0) $query->setParameter(2, $maxId);
        	if($limit!=null && $limit>0) $query->setMaxResults($limit);
        	return $query->getResult();
        }
        
        public function getStats($idVideo){
            $dql = "SELECT count(c.id) as nb, sum(m.mark) as total FROM $this->entity c JOIN c.video v JOIN c.mark m WHERE v.id = ?1";
            $query = $this->getEntityManager()->createQuery($dql)
                ->setParameter(1, $idVideo);
            $query->setMaxResults(1);
            return $query->getResult();
        }
        
        public function getByMarkId($id){
            $dql = "SELECT c FROM $this->entity c WHERE IDENTITY(c.mark) = ?1";
            $query = $this->getEntityManager()->createQuery($dql)
                ->setParameter(1, $id);
            $query->setMaxResults(1);
            $results = $query->getResult();
            return (($results==null)||(count($results)==0))?null:$results[0];
        }
        
        
    }
